//
//  ApplyForPayment.m
//  NtoccShipper
//
//  Created by mac on 2020/9/29.
//  Copyright © 2020 zhuchongjin. All rights reserved.
//
#import "ApplyForPayment.h"

 @interface ApplyForPayment(){
    int timeOld;
    NSTimer * _timer;
    
}

@property (nonatomic,strong) FlexFrameView *frameView;
@property (nonatomic,strong) CJLabel * labTitle;
@property (nonatomic,strong) CJLabel *labPayType;
@property (nonatomic,strong) CJLabel *labMoney;
@property (nonatomic,strong)  FlexTouchView *touchViewSure;
@property (nonatomic,copy) OnSureClick sureBlock;
@property (nonatomic,copy) OnCancleClick cancleBlock;
//view
@property (nonatomic,strong) UIView *viewSMSCodeBG;
@property (nonatomic,strong) CJTextField *fieldAouthCode;
@property (nonatomic,strong) CJLabel *labAouthTitle;
@property (nonatomic,strong) FlexTouchView *touchViewGetAouthCode;
@property (nonatomic,copy) NSString *strCode;
@property (nonatomic,copy) NSString *apreType;
@property (nonatomic,copy) NSString *strOrderCode;
@property (nonatomic,copy) NSString *strOutTradeNo;
@property (nonatomic,copy) NSString *strOrderNo;

@property (nonatomic,copy) NSString *strTotalAmount; //货主扣费金额

@property (nonatomic,copy) NSString *strPayType;


@end
@implementation ApplyForPayment

+ (ApplyForPayment *)shared {
    
    static dispatch_once_t predicate;
    
    static ApplyForPayment *objc;
    
    dispatch_once(&predicate, ^{
        
        objc = [[ApplyForPayment alloc] init];
        
    });
    
    return objc;
}

-(instancetype)initWithPayMentDic:(NSDictionary *)dic withPayTypeMsg:(NSString *)payType codes:(NSString *)strCode wayBillCode:(NSString *)strWayBillCode ApreType:(NSString *)apreType  ClickOnSure:(OnSureClick )sureClick ClickOnCancle:(OnCancleClick )cancleClick{
    
//    if (self = [super init]) {
          
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.backgroundColor = [[UIColor cjBlackColor] colorWithAlphaComponent:0.3];

        CGRect rcFrame = CGRectMake(0, 0, kScreenWidth - 40, 0);

        if (!self.frameView) {
            self.frameView = [[FlexFrameView alloc] initWithFlex:@"ApplyForPayment" Frame:rcFrame Owner:self];
        }
        self.frameView.flexibleHeight = YES;

        self.labTitle.font = [UIFont boldSystemFontOfSize:17];
        self.strOutTradeNo = @"";
        self.strOrderNo = @"";
        self.strTotalAmount = @"";

        self.strCode = strCode;
        self.strOrderCode = strWayBillCode;
    self.apreType = apreType;
        
        self.labPayType.text =  payType; //[CJControl getThreeUnaryValueStr:dic[@"payType"]];
        self.strPayType = [CJControl getThreeUnaryValueStr:dic[@"payType"]];
        CGFloat totalAmount = [[CJControl getThreeUnaryValueStr:dic[@"totalAmount"]] floatValue];
        self.strTotalAmount = [CJControl getThreeUnaryValueStr:dic[@"totalAmount"]];
        self.labMoney.text = CJStringWithFormat(@"%@元",@(totalAmount).cj_money_description);

        [self.frameView layoutIfNeeded];
        [self addSubview:self.frameView];

        NSString *needSmsCode = dic[@"needSmsCode"];
        if ([needSmsCode isEqualToString:@"yes"]) {
            self.viewSMSCodeBG.hidden = NO;
        }else{
            self.viewSMSCodeBG.hidden = YES;
        }

        self.frameView.center = self.center;
        self.fieldAouthCode.text = @"";
        
        
        if (self.viewSMSCodeBG.hidden == NO) {
            self.touchViewSure.userInteractionEnabled = NO;
            self.touchViewSure.backgroundColor = [UIColor cjLineBackGroundColor];
        }
        
        self.sureBlock = sureClick;
        self.cancleBlock = cancleClick;
//      }

      [self show];
      return self;
}


#pragma mark ----------获取验证码
- (void)btnTouchViewGetSMSCodeAction{
    DLog(@"获取验证码");
    
//    网商支付的
    NSString *strURLMyBank = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/shipmentBalancePaySendSmsCode",CJBaseUrl);
    NSDictionary *dicParMyBank = @{
        @"codes":[CJControl getThreeUnaryValueStr:self.strCode],
    };

// 云企付
    NSString *strURLYQF = CJStringWithFormat(@"%@/ntocc-tms-api/arpaTransfer/sendVerificationCode",CJBaseUrl);
    NSDictionary *dicParYQF = @{
        @"phone":[CJControl getLogInPhoneNum],
        @"source":@"shipment", //货主支付/平台支付货主传shipment平台platform
        @"amount":self.strTotalAmount
    };
    
    @weakify(self);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:[self.strPayType isEqualToString:@"arpa_2"] ? strURLYQF:strURLMyBank parameters:[self.strPayType isEqualToString:@"arpa_2"] ? dicParYQF:dicParMyBank status:OperationTip success:^(id  _Nonnull responseObject) {
        
        self.touchViewSure.userInteractionEnabled = YES;
        self.touchViewSure.backgroundColor = [UIColor cjWhiteColor];

        self.touchViewGetAouthCode.userInteractionEnabled = NO;
        timeOld = 60;
        [self startTimer];

        if ([self.strPayType isEqualToString:@"arpa_2"]) {
            //        {
            //            outTradeNo = "20093010582104900000152900096394",
            //            source = "shipment",
            //            branchCode = "27adb23841d547b8ae6f0c11481b4cfd",
            //            payeeType = "MERCHANT",
            //            orderNo = "202009783001141534",
            //            payeeId = "226801000000170811785",
            //            totalAmount = "58318060",
            //            body = "货主支付运费",
            //            payerMerchantId = "226801000000236401832",
            //        }

            self.strOutTradeNo = @"";
            self.strOrderNo = @"";

        }else{
            self.strOutTradeNo = [CJControl getThreeUnaryValueStr:responseObject[@"outTradeNo"]];
            self.strOrderNo = [CJControl getThreeUnaryValueStr:responseObject[@"orderNo"]];
        }
        
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}

#pragma mark ----------取消
- (void)btnTouchViewClickCancleAction{
    DLog(@"取消");
    [self endEditing:NO];
    [self hidden];
    
}

#pragma mark ----------确定
- (void)btnTouchViewClickSureAction{
    DLog(@"确定");
    [self endEditing:NO];
    
    if (self.viewSMSCodeBG.hidden == NO && [CJRegular getIsStrEmpty:self.fieldAouthCode.text]) {
        [CJAlert showStringDismissWithDelay:@"请填写验证码"];
        return;
    }
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/applicationForPayment",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"codes":self.strCode,
        @"payType":self.strPayType,
        @"outTradeNo":self.strOutTradeNo,
        @"orderNo":self.strOrderNo,
        @"smsCode":[CJControl getThreeUnaryValueStr:self.fieldAouthCode.text],
        @"payPlatform":self.apreType
    };
    
    @weakify(self);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        
        @strongify(self);
        if (self.sureBlock) {
            self.sureBlock(@"");
        }
        [self hidden];
    } failure:^(NSError * _Nonnull error) {
        
    }];

}

- (void)startTimer{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireOdlM) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    
    if (_timer == nil) {
        return;
    }
    [_timer invalidate];
    _timer = nil;
}

- (void)dealloc{
    
   NSLog(@"%s",__func__);
    [_timer invalidate];
    _timer = nil;
}

- (void)timerFireOdlM{
    
    NSString * str =[NSString stringWithFormat:@"%ds",timeOld];
    self.labAouthTitle.text = str;
    timeOld--;
    if (timeOld==0) {
        [self stopTimer];
        timeOld=60;
        self.labAouthTitle.text = @"获取验证码";
        self.touchViewGetAouthCode.userInteractionEnabled = YES;
        
    }
}


/// 展示隐藏
- (void)show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
//    _titleLabel.text = _title;
//    _msgLabel.text = _message;
    self.center = [UIApplication sharedApplication].keyWindow.center;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)hidden {
    
    @weakify(self);
    [UIView animateWithDuration:0.5 animations:^{
        
        @strongify(self);
        self.alpha = 0.0;
        self.labAouthTitle.text = @"获取验证码";
        [self stopTimer];
        timeOld=60;
        self.touchViewGetAouthCode.userInteractionEnabled = YES;
    }];
}
@end
